package org.itzheng.yuezhi.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.itzheng.yuezhi.R;
import org.itzheng.yuezhi.activity.WebViewActivity;
import org.itzheng.yuezhi.adapter.BaseRecyclerViewAdapter;
import org.itzheng.yuezhi.adapter.holder.LoadingViewHolder;
import org.itzheng.yuezhi.base.BaseFragment;
import org.itzheng.yuezhi.constant.HttpUrl;
import org.itzheng.yuezhi.entity.WeChatArticleSearchEntity;
import org.itzheng.yuezhi.utils.JsonUtils;
import org.itzheng.yuezhi.utils.MyGlide;
import org.itzheng.yuezhi.utils.MyLog;
import org.itzheng.yuezhi.utils.MyOkHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Title:微信文字分类下面的文章列表<br>
 * Description: <br>
 * Company: <br>
 *
 * @author ZhengYongdong
 * @email ItZheng@ZoHo.com
 * @date 2016/6/24 0024
 */
@SuppressLint("ValidFragment")
public class WeChatArticleContentFragment extends BaseFragment {
    private static final String TAG = "WeChatArticleContentFragment";
    View rootView;
    String mCid;
    String mName;
    int page = 1;
    int size = 20;
    RecyclerView rcv_wx_article;
    List<WeChatArticleSearchEntity.Result.Item> weChatArticleearchEntityResultList = new ArrayList<>();
    WeChatArticleSearchRecyclerViewAdapter weChatArticleSearchRecyclerViewAdapter;
    SwipeRefreshLayout srl_wx_article_refresh;
    MyOkHttp myOkHttp = MyOkHttp.getInstance();

    public WeChatArticleContentFragment(String cid, String name) {
        super();
        mCid = cid;
        mName = name;
    }

    public void initView() {
        if (weChatArticleSearchRecyclerViewAdapter == null) {
            srl_wx_article_refresh = (SwipeRefreshLayout) rootView.findViewById(R.id.srl_wx_article_refresh);
            srl_wx_article_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    initData();
                }
            });
            rcv_wx_article = (RecyclerView) rootView.findViewById(R.id.rcv_wx_article);
            final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            rcv_wx_article.setLayoutManager(linearLayoutManager);
            weChatArticleSearchRecyclerViewAdapter = new WeChatArticleSearchRecyclerViewAdapter(getActivity(), weChatArticleearchEntityResultList);
            rcv_wx_article.setAdapter(weChatArticleSearchRecyclerViewAdapter);
            weChatArticleSearchRecyclerViewAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void OnItemClick(View view, int position) {
                    if (position >= weChatArticleearchEntityResultList.size()) {
                        return;
                    }
                    Intent intent = new Intent(getContext(), WebViewActivity.class);
                    intent.putExtra("url", weChatArticleearchEntityResultList.get(position).getSourceUrl());
                    startActivity(intent);
                }
            });
            //设置滑动监听,用于加载更多
            rcv_wx_article.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    //获取最后一个可见的item
                    if (weChatArticleearchEntityResultList.size() <= linearLayoutManager.findLastVisibleItemPosition()) {
                        getNetData();
                    }
                }
            });
        } else {
            weChatArticleSearchRecyclerViewAdapter.notifyDataSetChanged();
            srl_wx_article_refresh.setRefreshing(false);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container) {
        if (rootView == null) {
            rootView = View.inflate(getActivity(), R.layout.fragment_wechat_article_content, null);
            initData();
        }
        return rootView;
    }

    private void initData() {
        page = 1;
        getNetData();
    }

    private void getNetData() {
        if (weChatArticleearchEntityResultList == null || weChatArticleearchEntityResultList.isEmpty()) {
            showProgressDialog();
        }
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("key", HttpUrl.MOB_API_KEY);
        hashMap.put("cid", mCid);
        hashMap.put("page", page);
        hashMap.put("size", size);
        //请求数据前,先取消,避免造成多个数据同时返回的问题
        myOkHttp.cancelAll();
        myOkHttp.getUrl(HttpUrl.WX_ARTICLE_SEARCH, hashMap, new MyOkHttp.RequestCallBack() {
            @Override
            public void onFailure(Exception httpException, String describe) {
                parseJson(null);
            }

            @Override
            public void onSuccess(String result) {
                parseJson(result);
            }
        });
    }

    private void parseJson(String result) {
        MyLog.json(result);
        WeChatArticleSearchEntity weChatArticleearchEntity = JsonUtils.fromJson(result, WeChatArticleSearchEntity.class);
        if (page == 1) {
            weChatArticleearchEntityResultList.clear();
        }
        if (weChatArticleearchEntity == null || weChatArticleearchEntity.getResult() == null || weChatArticleearchEntity.getResult().getList() == null) {


        } else {
            List<WeChatArticleSearchEntity.Result.Item> itemList = weChatArticleearchEntity.getResult().getList();
            if (itemList != null)//去除重复数据
                for (int i = 0; i < itemList.size(); i++) {
                    if (weChatArticleearchEntityResultList.contains(itemList.get(i))) {
                        itemList.remove(i);
                        i--;
                    } else {
                        weChatArticleearchEntityResultList.add(itemList.get(i));
                    }
                }
            page++;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dismissProgressDialog();
                initView();
            }
        });
    }

    public class WeChatArticleSearchRecyclerViewAdapter extends BaseRecyclerViewAdapter {
        private final int TYPE_CONTENT = 0;
        private final int TYPE_LOADING = 1;

        List<WeChatArticleSearchEntity.Result.Item> mWeChatArticleearchEntityResultList;
        Context mContext;

        public WeChatArticleSearchRecyclerViewAdapter(Context context, List<WeChatArticleSearchEntity.Result.Item> weChatArticleearchEntityResultList) {
            mWeChatArticleearchEntityResultList = weChatArticleearchEntityResultList;
            mContext = context;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == getItemCount() - 1) {
                return TYPE_LOADING;
            } else {
                return TYPE_CONTENT;
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MyLog.i(TAG, "viewType=" + viewType);
            switch (viewType) {
                case TYPE_CONTENT:
                    View view = View.inflate(mContext, R.layout.item_wechat_article_content, null);
                    WeChatArticleSearchViewHolder weChatArticleSearchViewHolder =
                            new WeChatArticleSearchViewHolder(view);
                    //是否复用
                    weChatArticleSearchViewHolder.setIsRecyclable(false);
                    weChatArticleSearchViewHolder.tv_wechat_article_title = (TextView) view.findViewById(R.id.tv_wechat_article_title);
                    weChatArticleSearchViewHolder.iv_wechat_article_thumbnails = (ImageView) view.findViewById(R.id.iv_wechat_article_thumbnails);
                    weChatArticleSearchViewHolder.tv_wechat_article_pubTime = (TextView) view.findViewById(R.id.tv_wechat_article_pubTime);
                    return weChatArticleSearchViewHolder;
                case TYPE_LOADING:
                    LoadingViewHolder loadingViewHolder = new LoadingViewHolder(View.inflate(mContext, R.layout.loading_progress, null));
                    return loadingViewHolder;
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, boolean isBaseRecyclerViewAdapter) {
            if (holder instanceof WeChatArticleSearchViewHolder) {
                WeChatArticleSearchEntity.Result.Item item = mWeChatArticleearchEntityResultList.get(position);
                WeChatArticleSearchViewHolder weChatArticleSearchViewHolder = (WeChatArticleSearchViewHolder) holder;
                weChatArticleSearchViewHolder.tv_wechat_article_title.setText(item.getTitle() + "");
                String[] imgs = null;
                MyLog.i(TAG, "position=" + position);
                if (item.getThumbnails() == null) {

                } else {
                    imgs = item.getThumbnails().split("\\$");
                }
                if (imgs == null || imgs.length == 0) {
                    //没有图片就隐藏控件,
                    weChatArticleSearchViewHolder.iv_wechat_article_thumbnails.setVisibility(View.INVISIBLE);
                } else {
                    MyLog.i(TAG, "getThumbnails imgs[0]=" + imgs[0]);
                    //设置图片
                    MyGlide.getInstance()
                            .setImage(imgs[0], weChatArticleSearchViewHolder.iv_wechat_article_thumbnails);
                }
                weChatArticleSearchViewHolder.tv_wechat_article_pubTime.setText(item.getPubTime() + "");
            }
        }


        @Override
        public int getItemCount() {
            if (mWeChatArticleearchEntityResultList == null || mWeChatArticleearchEntityResultList.isEmpty()) {
                return 0;
            }
            return mWeChatArticleearchEntityResultList.size() + 1;
        }


        /**
         * 分类下的文章类表
         */
        class WeChatArticleSearchViewHolder extends RecyclerView.ViewHolder {
            /**
             * 文章标题
             */
            TextView tv_wechat_article_title;
            /**
             * 缩略图
             */
            ImageView iv_wechat_article_thumbnails;
            /**
             * 发布时间
             */
            TextView tv_wechat_article_pubTime;

            public WeChatArticleSearchViewHolder(View itemView) {
                super(itemView);
            }
        }
    }
}
